import { login, register, getUserInfo, updateUserInfo } from '@/api/user'

export default {
  namespaced: true,
  state: {
    userInfo: null,
    userId: localStorage.getItem('userId') || null,
    token: localStorage.getItem('token') || null
  },
  getters: {
    userId: state => state.userInfo?.id
  },
  mutations: {
    SET_USER_INFO(state, info) {
      state.userInfo = info
      if (info?.id) {
        state.userId = info.id
        localStorage.setItem('userId', info.id)
        localStorage.setItem('userInfo', JSON.stringify(info))
      }
    },
    SET_TOKEN(state, token) {
      state.token = token
      if (token) {
        localStorage.setItem('token', token)
      } else {
        localStorage.removeItem('token')
      }
    },
    SET_THEME(state, theme) {
      state.theme = theme
      localStorage.setItem('theme', theme)
      document.documentElement.setAttribute('data-theme', theme)
    },
    CLEAR_USER(state) {
      state.userInfo = null
      state.token = null
      state.userId = null
      localStorage.removeItem('token')
      localStorage.removeItem('userId')
      localStorage.removeItem('userInfo')
    }
  },
  actions: {
    async login({ commit, dispatch }, credentials) {
      try {
        const res = await login(credentials)
        if ((res.code === 0 && res.success) || res.message === '获取成功') {
          const userId = parseInt(res.data)
          if (userId) {
            localStorage.setItem('userId', userId)
            commit('SET_USER_INFO', { id: userId })
            const tempToken = `temp_token_${userId}_${Date.now()}`
            commit('SET_TOKEN', tempToken)
            localStorage.setItem('token', tempToken)
            await dispatch('getUserInfo')
            return res.data
          } else {
            console.warn('登录响应中未找到用户ID:', res.data)
            throw new Error('登录响应中缺少用户ID')
          }
        }
        if (res.message !== '获取成功') {
          throw new Error(res.message || '登录失败，请检查用户名和密码')
        }
      } catch (error) {
        if (error.message === '获取成功') {
          return error.message
        }
        console.error('登录失败:', error)
        commit('CLEAR_USER')
        throw error
      }
    },

    async register({ commit }, registerForm) {
      try {
        const formData = {
          username: registerForm.username,
          password: registerForm.password,
          email: registerForm.email,
          gender: '未设置',
          userId: 0
        }
        
        const res = await register(formData)
        if (res.code === 200) {
          if (res.data) {
            commit('SET_TOKEN', res.data.token)
            if (res.data.id) {
              localStorage.setItem('userId', res.data.id)
              if (registerForm.gender) {
                await updateUserInfo({
                  id: res.data.id,
                  gender: registerForm.gender === 'male' ? '男' : '女'
                })
              }
            }
          }
          return res.data || true
        }
        if (res.message === 'success' || res.message === '注册成功') {
          return true
        }
        throw new Error(res.message || '注册失败')
      } catch (error) {
        console.error('注册失败:', error)
        commit('CLEAR_USER')
        if (error.response?.data?.message) {
          throw new Error(error.response.data.message)
        }
        throw new Error(error.message || '注册失败，请稍后重试')
      }
    },

    async getUserInfo({ commit }) {
      try {
        const res = await getUserInfo()
        if (res.code === 200 && res.data) {
          const userInfo = {
            ...res.data,
            nickname: res.data.nickname || '',
            avatar: res.data.avatar || `${process.env.VUE_APP_API_URL || ''}/api/user/avatar?userId=${res.data.id}`,
            id: parseInt(res.data.id)
          }
          commit('SET_USER_INFO', userInfo)
          return userInfo
        }
        throw new Error(res.message || '获取用户信息失败')
      } catch (error) {
        console.error('获取用户信息失败:', error)
        commit('CLEAR_USER')
        throw error
      }
    },

    toggleTheme({ commit, state }) {
      const newTheme = state.theme === 'light' ? 'dark' : 'light'
      commit('SET_THEME', newTheme)
    },

    async updateUserInfo({ commit }, userData) {
      try {
        const res = await updateUserInfo(userData)
        if ((res.code === 0 && res.success) || res.message === '获取成功') {
          const userInfo = {
            ...res.data,
            id: userData.id || localStorage.getItem('userId')
          }
          commit('SET_USER_INFO', userInfo)
          return userInfo
        }
        if (res.message !== '获取成功') {
          throw new Error(res.message || '更新用户信息失败')
        }
      } catch (error) {
        if (error.message === '获取成功') {
          return error.message
        }
        console.error('更新用户信息失败:', error)
        throw error
      }
    }
  }
} 